package com.zwcl.common.core.utils;

import com.zwcl.common.core.exception.BaseException;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @Description 排序工具类
 * @Author Jason
 * @Date 2019/10/12 13:55
 * @Email jason@wetax.com.cn
 */
public final class ParamSortUtils {

    /**
     * 根据Map key进行升序排序
     *
     * @param map 待处理map
     * @return 处理结果
     */
    public static Map<String, Object> sortMapByKeyToAsc(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, Object> sortMap = new TreeMap<>(String::compareTo);

        sortMap.putAll(map);
        return sortMap;
    }

    /**
     * 签名参数排序
     *
     * @param params
     * @return
     */
    public static String ASCIISort(Map<String, Object> params) throws BaseException {
        //所有参与传参的参数按照accsii排序（升序）
        Set<String> keySet = params.keySet();
        Map<String, String> map = new TreeMap<String, String>();
        for (String key1 : keySet) {
            map.put(key1, StringUtilsEx.toString(params.get(key1)));
        }
        StringBuilder plainmsg = new StringBuilder();
        for (Map.Entry<String, String> element : map.entrySet()) {
            if (!"signature".equals(element.getKey()) && !StringUtilsEx.isEmpty(element.getValue())) {
                plainmsg.append("&" + element.getKey().trim() + "=" + element.getValue());
            }
        }
        return plainmsg.toString();
    }
}
